/**
 * 北京中流科技有限公司 版权所有
 * http://www.chinasoa.com.cn
 */
package cn.com.chinasoa.archive.runtime;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import javax.jcr.LoginException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.portlet.ActionRequest;
import javax.portlet.PortletRequest;

import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.core.config.RepositoryConfig;

import cn.com.chinasoa.archive.portlet.ArchiveUploadHelper;
import cn.com.chinasoa.archive.portlet.model.Archive;

import com.x4ee.soa.portal.framework.core.FrameworkConfig;

/**
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2007-8-1下午05:48:54
 */
public class ArchiveRuntime {
	
	public static final String X4EE_ARCHIVE_RUNTIME_REPOSITORY="x4ee.archive.runtime.repository";

	/**
	 * 获取或创建存储库
	 * @param tPortletRequest
	 * @param portletName
	 * @return
	 */
	public static Repository getRepository(PortletRequest tPortletRequest,String portletName){
		Repository repository = getRepository(tPortletRequest);
		if(repository!=null)return repository;
		String portletAppPath = tPortletRequest.getPortletSession().getPortletContext().getRealPath("");
		File portletAppDir = new File(portletAppPath);
		if((portletAppDir!=null)&&(portletAppDir.exists())&&(portletAppDir.isDirectory())){
			File portletsDir = new File(portletAppDir,"portlets");
			if((portletsDir!=null)&&(portletsDir.exists())&&(portletsDir.isDirectory())){
				File portletDir = new File(portletsDir,portletName);
				if((portletDir!=null)&&(portletDir.exists())&&(portletDir.isDirectory())){
					File xmlDir = new File(portletDir,"xml");
					if((xmlDir!=null)&&(xmlDir.exists())&&(xmlDir.isDirectory())){
						try {
							FileInputStream repXmlIS = new FileInputStream(new File(xmlDir,"repository.xml"));
							RepositoryConfig tRepositoryConfig = RepositoryConfig.create(repXmlIS,portletDir.getAbsolutePath());
							repository= new TransientRepository(tRepositoryConfig);
							tPortletRequest.getPortletSession().getPortletContext().setAttribute(X4EE_ARCHIVE_RUNTIME_REPOSITORY,repository);							
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return repository;
	}

	/**
	 * 获取存储库
	 * @param tPortletRequest
	 * @return
	 */
	public static Repository getRepository(PortletRequest tPortletRequest){
		Object tRepositoryObj = tPortletRequest.getPortletSession().getPortletContext().getAttribute(X4EE_ARCHIVE_RUNTIME_REPOSITORY);
		if((tRepositoryObj!=null)&&(tRepositoryObj instanceof Repository)){
			return (Repository)tRepositoryObj;
		}else{
			return null;
		}
	}

	/**
	 * 获取存储库
	 * @param frameworkConfig
	 * @return
	 */
	public static Repository getRepository(FrameworkConfig frameworkConfig){
		Object tRepositoryObj = frameworkConfig.getPortletConfig().getPortletContext().getAttribute(X4EE_ARCHIVE_RUNTIME_REPOSITORY);
		if((tRepositoryObj!=null)&&(tRepositoryObj instanceof Repository)){
			return (Repository)tRepositoryObj;
		}else{
			return null;
		}
	}

	/**
	 * 创建存储库
	 * @param frameworkConfig
	 * @return
	 */
	public static Repository createRepository(FrameworkConfig frameworkConfig){
		Repository repository = getRepository(frameworkConfig);
		if(repository!=null)return repository;
		String portletAppPath = frameworkConfig.getPortletContext().getRealPath("");
		File portletAppDir = new File(portletAppPath);
		if((portletAppDir!=null)&&(portletAppDir.exists())&&(portletAppDir.isDirectory())){
			File portletsDir = new File(portletAppDir,"portlets");
			if((portletsDir!=null)&&(portletsDir.exists())&&(portletsDir.isDirectory())){
				File portletDir = new File(portletsDir,frameworkConfig.getPortletName());
				if((portletDir!=null)&&(portletDir.exists())&&(portletDir.isDirectory())){
					File xmlDir = new File(portletDir,"xml");
					if((xmlDir!=null)&&(xmlDir.exists())&&(xmlDir.isDirectory())){
						try {
							FileInputStream repXmlIS = new FileInputStream(new File(xmlDir,"repository.xml"));
							String aPath = portletDir.getAbsolutePath();
							RepositoryConfig tRepositoryConfig = RepositoryConfig.create(repXmlIS,aPath);
							repository= new TransientRepository(tRepositoryConfig);
							frameworkConfig.getPortletConfig().getPortletContext().setAttribute(X4EE_ARCHIVE_RUNTIME_REPOSITORY,repository);							
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return repository;	
	}
	
	public static boolean storeArchive(ActionRequest actionRequest,Repository tRepository,String archiveName,String archiveTitle,InputStream input,String archiveUser){
		boolean result = false;
		if((tRepository!=null)&&(archiveName!=null)&&(archiveTitle!=null)&&(input!=null)&&( archiveUser!=null)){
			Session session = null;
			try {
				session = tRepository.login(new SimpleCredentials(ArchiveUploadHelper.SEP,ArchiveUploadHelper.X4EE.toCharArray()));
	            Node root = session.getRootNode();
	            String nodeName = ArchiveUploadHelper.ARCHIVE_PREX+System.currentTimeMillis();
	            Node archiveNode = root.addNode(nodeName);

	            archiveNode.setProperty(ArchiveUploadHelper.ARCHIVE_NAME,archiveName);
	            archiveNode.setProperty(ArchiveUploadHelper.ARCHIVE_TITLE,archiveTitle);
	            archiveNode.setProperty(ArchiveUploadHelper.ARCHIVE_USER,archiveUser);            
	            archiveNode.setProperty(ArchiveUploadHelper.ARCHIVE_FILE,input);
	            Calendar archiveCalendar= new GregorianCalendar();
	            archiveNode.setProperty(ArchiveUploadHelper.ARCHIVE_CALENDAR,archiveCalendar);
	            session.save();

				Map archiveModelMap = new HashMap();

		        for(NodeIterator nIt = root.getNodes();nIt.hasNext();){
		        	Node tArchiveNode = (Node)nIt.next();
		            String tArchiveNodeName = tArchiveNode.getName();
		            if((tArchiveNodeName!=null)&&(tArchiveNodeName.startsWith(ArchiveUploadHelper.ARCHIVE_PREX))){
		            	Property tArchiveNamePty = tArchiveNode.getProperty(ArchiveUploadHelper.ARCHIVE_NAME);
				        Property tArchiveTitlePty = tArchiveNode.getProperty(ArchiveUploadHelper.ARCHIVE_TITLE);
				        Property tArchiveUserPty = tArchiveNode.getProperty(ArchiveUploadHelper.ARCHIVE_USER);
				        Property archiveCalenderPty = tArchiveNode.getProperty(ArchiveUploadHelper.ARCHIVE_CALENDAR);
				        
				        String tArchiveName = tArchiveNamePty.getValue().getString();
				        String tArchiveTitle = tArchiveTitlePty.getValue().getString();
				        String tArchiveUser = tArchiveUserPty.getValue().getString();
				        Calendar tArchiveCalender = archiveCalenderPty.getValue().getDate();
				        
				        Archive tArchive = new Archive();
				        tArchive.setName(tArchiveName);
				        tArchive.setNodeName(tArchiveNodeName);
				        tArchive.setTitle(tArchiveTitle);
				        tArchive.setUser(tArchiveUser);
				        tArchive.setCalendar(tArchiveCalender);
				        
				        archiveModelMap.put(tArchiveNodeName,tArchive);
		            }
		        }
		        actionRequest.getPortletSession().setAttribute(ArchiveUploadHelper.ARCHIVE_MODEL_MAP,archiveModelMap); 				
	            result = true;
			} catch (LoginException e) {
				e.printStackTrace();
			} catch (RepositoryException e) {
				e.printStackTrace();
			}finally {
				if(session!=null)session.logout();
			}
		}
		return result;
	}

}
